/**
 * Created by asus on 2017/7/18.
 */
import * as http from 'http'
import * as url from 'url'
import * as querystring from 'querystring'
import {CONTENT_TYPE} from "./constant";

export class Dispatcher implements IDispatcher {

    get(path: string, callback: any): void {
        let urlObject = url.parse(path);
        let option = {
            method: 'GET',
            hostname: urlObject.hostname,
            port: urlObject.port,
            path: urlObject.path,
            headers: {// 必选信息
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
            }
        };

        let dispose = function (response) {
            let body = '';
            response.on('data', function (data) {
                body += data;
            });
            response.on('end', function () {
                // console.log(body);
                callback(body);
            });
        };

        let req = http.request(option, dispose);

        req.end();
    }

    post(path: string, data: any, callback: any, contentType: string = 'FORM'): void {

        let urlObject = url.parse(path);

        let contents;
        let headers = {
            "content-type": `${CONTENT_TYPE[contentType]}; charset=UTF-8`
        };

        if (contentType === 'JSON') {
            contents = JSON.stringify(data);
        } else {
            contents = querystring.stringify(data);
            Object.assign(headers, {
                "Content-Length": contents.length, // 请求长度, 通过上面计算得到
            });
        }

        let option = {
            method: 'POST',
            hostname: urlObject.hostname,
            port: urlObject.port,
            path: urlObject.path,
            headers: headers
            // headers: {// 必选信息
            //     "Content-Type": `${CONTENT_TYPE[contentType]}; charset=UTF-8`,
            //     "Content-Length": contents.length, // 请求长度, 通过上面计算得到
            // }
        };

        let dispose = function (response) {
            let body = '';
            response.on('data', function (data) {
                body += data;
            });
            response.on('end', function () {
                // console.log(body);
                callback(body);
            });
        };

        let req = http.request(option, dispose);

        req.write(contents);//发送内容
        req.end();
    }
}


